package org.jeecg.modules.bl.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.vo.ArcAccountCusVO;
import org.jeecg.modules.bl.entity.BlExpenses;
import org.jeecg.modules.bl.entity.BlSubExpenses;
import org.jeecg.modules.bl.service.IBlExpensesService;
import org.jeecg.modules.bl.service.IBlSubExpensesService;
import org.jeecg.modules.bl.vo.BlExpensesPage;
import org.jeecg.modules.bl.vo.ChgFeeItemVo;
import org.jeecg.modules.chg.entity.ChgPayments;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 计费清单
 * @Author: jeecg-boot
 * @Date:   2022-02-13
 * @Version: V1.0
 */
@Api(tags="计费清单")
@RestController
@RequestMapping("/bl/blExpenses")
@Slf4j
public class BlExpensesController {
	@Autowired
	private IBlExpensesService blExpensesService;
	@Autowired
	private IBlSubExpensesService blSubExpensesService;
	 @Autowired
	 private IArcAccountService arcAccountService;

	/**
	 * 分页列表查询
	 *
	 * @param blExpenses
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "计费清单-分页列表查询")
	@ApiOperation(value="计费清单-分页列表查询", notes="计费清单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BlExpenses blExpenses,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		blExpenses.setIsValid(1);
		blExpenses.setDelFlag(0);
		QueryWrapper<BlExpenses> queryWrapper = QueryGenerator.initQueryWrapper(blExpenses, req.getParameterMap());
		Page<BlExpenses> page = new Page<BlExpenses>(pageNo, pageSize);
		IPage<BlExpenses> pageList = blExpensesService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	/**
	 * 杂项列表-分页列表查询
	 *
	 * @param blExpenses
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "杂项列表-分页列表查询")
	@ApiOperation(value="杂项列表-分页列表查询", notes="杂项列表-分页列表查询")
	@GetMapping(value = "/alienList")
	public Result<?> queryPageAlienList(BlExpenses blExpenses,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<BlExpenses> queryWrapper = QueryGenerator.initQueryWrapper(blExpenses, req.getParameterMap());
		queryWrapper.gt("alien_money",0);
		Page<BlExpenses> page = new Page<BlExpenses>(pageNo, pageSize);
		IPage<BlExpenses> pageList = blExpensesService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	/**
	 * 水费账单
	 *
	 * @param chgPayments
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "水费账单")
	@ApiOperation(value="水费账单", notes="水费账单")
	@GetMapping(value = "/getFeeBill")
	public Result<?> getFeeBill(ChgPayments chgPayments,
								@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								HttpServletRequest req) {
		String accCode="";
		String accName="";
		JSONObject billObj=new JSONObject();
		JSONArray fdObj=new JSONArray();
		List<String>cusLs=new ArrayList<>();
		Map<String,String>cusMap=new HashMap<>();
		BigDecimal feeMoney = new BigDecimal(0.0);

//		if(oConvertUtils.isNotEmpty(TenantContext.getTenant())){
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String tenantIds = sysUser.getRelTenantIds();
			if (oConvertUtils.isNotEmpty(tenantIds)) {
				List<String> tenantIdList = Arrays.asList(tenantIds.split(","));
				TenantContext.setTenant(tenantIdList.get(0));
			}
//		}

		List<ArcAccountCusVO> arcAccountCusVOS = arcAccountService.queryAccount(chgPayments.getAccountId()
				, null, chgPayments.getAccCode());
		if(null !=arcAccountCusVOS && arcAccountCusVOS.size()>0){
			ArcAccountCusVO accountCusVO = arcAccountCusVOS.get(0);
			accCode=accountCusVO.getAccCode();
			accName=accountCusVO.getAccName();

			for (ArcAccountCusVO cusVO : arcAccountCusVOS) {
				cusLs.add(cusVO.getCode());
				cusMap.put(cusVO.getCusId(),cusVO.getCode());
			}
		}

		if(oConvertUtils.isEmpty(chgPayments.getCreateTimeBegin())){
			chgPayments.setCreateTimeBegin(DateUtils.getFirstMonth());
		}

		if(oConvertUtils.isEmpty(chgPayments.getCreateTimeEnd())){
			chgPayments.setCreateTimeEnd(DateUtils.getDate("yyyy-MM-dd"));
		}

		List<ChgFeeItemVo> chgFeeItemVos = blExpensesService.queryFeeBill(cusLs, chgPayments.getCreateTimeBegin(), chgPayments.getCreateTimeEnd());

		if(null != chgFeeItemVos && chgFeeItemVos.size()>0){
			feeMoney = chgFeeItemVos.stream().map(e -> e.getMoney()).reduce(BigDecimal::add).get();//求和
		}

		// List<BlExpenses> expensesList = blExpensesService.list(new LambdaQueryWrapper<BlExpenses>()
		// 		.eq(BlExpenses::getDelFlag, 0).eq(BlExpenses::getIsValid, 1)
		// 		.in(BlExpenses::getCustomerId, cusLs)
		// 		.between(BlExpenses::getCreateTime, chgPayments.getCreateTimeBegin(), chgPayments.getCreateTimeEnd()));
		//
		// for (BlExpenses fee : expensesList) {
		// 	JSONObject feeObj =new JSONObject();
		// 	feeObj.put("cusName",fee.getCusName());
		// 	feeObj.put("cusCode",fee.getCustomerId());
		// 	feeObj.put("readMonth",fee.getReadMonth());
		//
		// 	feeObj.put("amount",fee.getAmount());
		// 	feeObj.put("totalMoney",fee.getTotalMoney());
		// 	feeObj.put("alienMoney",fee.getAlienMoney().add(fee.getVatMoney())
		// 			.add(fee.getPenalty()).add(fee.getLjMoney())
		// 			.add(fee.getWuMoney()).setScale(2,BigDecimal.ROUND_FLOOR));
		// 	feeObj.put("money",fee.getMoney());
		// 	feeMoney=feeMoney.add(fee.getMoney());
		// 	fdObj.add(feeObj);
		// }

		billObj.put("accName",accName);
		billObj.put("accCode",accCode);
		billObj.put("feeNumber",chgFeeItemVos.size()>0 ? chgFeeItemVos.size() : 0);
		billObj.put("feeMoney",feeMoney);
		billObj.put("feeDetail",chgFeeItemVos);

		return Result.OK(billObj);
	}

	/**
	 *   添加
	 *
	 * @param blExpensesPage
	 * @return
	 */
	@AutoLog(value = "计费清单-添加")
	@ApiOperation(value="计费清单-添加", notes="计费清单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BlExpensesPage blExpensesPage) {
		BlExpenses blExpenses = new BlExpenses();
		BeanUtils.copyProperties(blExpensesPage, blExpenses);
//		blExpensesService.saveMain(blExpenses, blExpensesPage.getBlSubExpensesList());
		return Result.OK("添加成功！");
	}
	/**
	 *   杂项录入-添加
	 *
	 * @param blExpensesPage
	 * @return
	 */
	@AutoLog(value = "杂项录入-添加")
	@ApiOperation(value="计费清单-添加", notes="计费清单-添加")
	@PostMapping(value = "/addAlien")
	public Result<?> addAlien(@RequestBody BlExpensesPage blExpensesPage) {
		if(oConvertUtils.isNotEmpty(blExpensesPage.getCustomerId())){
			String[] cusIds = blExpensesPage.getCustomerId().split(",");
			String[] cusNames = blExpensesPage.getCusName().split(",");
			for (int i = 0; i < cusIds.length; i++) {
				BlExpenses blExpenses = new BlExpenses();
				BeanUtils.copyProperties(blExpensesPage, blExpenses);

				BeanUtils.copyProperties(blExpensesPage,blExpenses);
				blExpenses.setCustomerId(cusIds[i]);
				blExpenses.setCusName(cusNames[i]);
				blExpensesService.saveAlienMain(blExpenses, blExpensesPage.getBlSubExpensesList());
			}
			return Result.OK("添加成功！");
		}
		return Result.error("添加异常！");
	}

	/**
	 *  编辑
	 *
	 * @param blExpensesPage
	 * @return
	 */
	@AutoLog(value = "计费清单-编辑")
	@ApiOperation(value="计费清单-编辑", notes="计费清单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BlExpensesPage blExpensesPage) {
		BlExpenses blExpenses = new BlExpenses();
		BeanUtils.copyProperties(blExpensesPage, blExpenses);
		BlExpenses blExpensesEntity = blExpensesService.getById(blExpenses.getId());
		if(blExpensesEntity==null) {
			return Result.error("未找到对应数据");
		}
		blExpensesService.updateMain(blExpenses, blExpensesPage.getBlSubExpensesList());
		return Result.OK("编辑成功!");
	}
	/**
	 *  杂项编辑
	 *
	 * @param blExpensesPage
	 * @return
	 */
	@AutoLog(value = "杂项-编辑")
	@ApiOperation(value="杂项-编辑", notes="杂项-编辑")
	@PutMapping(value = "/editAlien")
	public Result<?> editAlien(@RequestBody BlExpensesPage blExpensesPage) {
		return Result.OK("杂项不允许编辑!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计费清单-通过id删除")
	@ApiOperation(value="计费清单-通过id删除", notes="计费清单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		blExpensesService.delMain(id);
		return Result.OK("删除成功!");
	}
	/**
	 *   杂项通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "杂项-通过id删除")
	@ApiOperation(value="杂项-通过id删除", notes="杂项-通过id删除")
	@DeleteMapping(value = "/alienDelete")
	public Result<?> alienDelete(@RequestParam(name="id",required=true) String id) {
		blExpensesService.delAlienMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "计费清单-批量删除")
	@ApiOperation(value="计费清单-批量删除", notes="计费清单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.blExpensesService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "计费清单-批量删除")
	@ApiOperation(value="计费清单-批量删除", notes="计费清单-批量删除")
	@DeleteMapping(value = "/deleteAlienBatch")
	public Result<?> deleteAlienBatch(@RequestParam(name="ids",required=true) String ids) {
		//this.blExpensesService.delAlienBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("不允许批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计费清单-通过id查询")
	@ApiOperation(value="计费清单-通过id查询", notes="计费清单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BlExpenses blExpenses = blExpensesService.getById(id);
		if(blExpenses==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(blExpenses);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计费明细通过主表ID查询")
	@ApiOperation(value="计费明细主表ID查询", notes="计费明细-通主表ID查询")
	@GetMapping(value = "/queryBlSubExpensesByMainId")
	public Result<?> queryBlSubExpensesListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BlSubExpenses> blSubExpensesList = blSubExpensesService.selectByMainId(id);
		//List<String> NatureIds = blSubExpensesList.stream().map(BlSubExpenses::getNatureId).collect(Collectors.toList());
		return Result.OK(blSubExpensesList);
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "计费明细通过主表ID查询")
	@ApiOperation(value="计费明细主表ID查询", notes="计费明细-通主表ID查询")
	@GetMapping(value = "/queryAlienBlSubExpensesByMainId")
	public Result<?> queryAlienBlSubExpensesByMainId(@RequestParam(name="id",required=true) String id) {
		List<BlSubExpenses> blSubExpensesList = blSubExpensesService.selectAlienByMainId(id);
		return Result.OK(blSubExpensesList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param blExpenses
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BlExpenses blExpenses) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BlExpenses> queryWrapper = QueryGenerator.initQueryWrapper(blExpenses, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<BlExpenses> queryList = blExpensesService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<BlExpenses> blExpensesList = new ArrayList<BlExpenses>();
      if(oConvertUtils.isEmpty(selections)) {
          blExpensesList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          blExpensesList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<BlExpensesPage> pageList = new ArrayList<BlExpensesPage>();
      for (BlExpenses main : blExpensesList) {
          BlExpensesPage vo = new BlExpensesPage();
          BeanUtils.copyProperties(main, vo);
          List<BlSubExpenses> blSubExpensesList = blSubExpensesService.selectByMainId(main.getId());
          vo.setBlSubExpensesList(blSubExpensesList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "计费清单列表");
      mv.addObject(NormalExcelConstants.CLASS, BlExpensesPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("计费清单数据", "导出人:"+sysUser.getRealname(), "计费清单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BlExpensesPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BlExpensesPage.class, params);
              for (BlExpensesPage page : list) {
                  BlExpenses po = new BlExpenses();
                  BeanUtils.copyProperties(page, po);
                  blExpensesService.saveMain(po, page.getBlSubExpensesList(),"1");
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
